package com.bwie.auth.handler;

import com.bwie.auth.exceptions.BizException;
import com.bwie.common.result.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Log4j2
public class GlobaExceptionHandler {
    /**
     * 业务异常处理
     */
    @ExceptionHandler(BindException.class)
    public Result bizExceptionHandler(BizException bizException){
        log.error("义务异常,异常信息:{}",bizException);
        String message = bizException.getMessage();
        return Result.error(message);
    }
    /**
     * 参数验证不通过异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException methodArgumentNotValidException){
        //通过异常获取所有的错误
        BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        //遍历获取每一个异常信息
        StringBuilder stringBuilder = new StringBuilder();
        allErrors.forEach(error ->{
            String defaultMessage = error.getDefaultMessage();
            stringBuilder.append(defaultMessage+";");
        });
        log.error("参数验证不通过异常,异常信息：{}",stringBuilder.toString());
        return Result.error(stringBuilder.toString());

    }



}
